<template>
  <div class="scroll">
    <div class="map-title">企业地图 (提示: 请通过放大移动确定位置后点击确认)</div>
    <div class="map-sub-title">点击坐标: [{{latitude}}, {{longitude}}]</div>
    <div ref="map" class="map-wrapper">正在初始化地图</div>
  </div>
</template>

<script>
  import initializeMap from "@/config/map";

  export default {
    name: "ui_map_view",
    data() {
      return {
        latitude: 29.61997,
        longitude: 106.537704,
      };
    },
    mounted() {
      initializeMap().then(BMap => {
        let point = {};
        if (this.latitude && this.longitude) {
          point = {
            latitude: this.latitude,
            longitude: this.longitude
          };
        }
        this.initMap(BMap, point);
      });
    },
    methods: {
      initMap(BMap, point) {
        const map = new BMap.Map(this.$refs.map);
        map.centerAndZoom(new BMap.Point(116.404, 39.915), 16);
        map.addControl(new BMap.NavigationControl());

        const setMaker = p => {
          map.clearOverlays();
          const marker = new BMap.Marker(new BMap.Point(p.lng, p.lat));
          map.addOverlay(marker);
          this.longitude = p.lng;
          this.latitude = p.lat;
        };

        !this.unEditable && map.addEventListener("click", e => {
          setMaker(e.point);
        });

        if (point.latitude && point.latitude) {
          setMaker({
            lng: point.longitude,
            lat: point.latitude
          });
          map.centerAndZoom(new BMap.Point(point.longitude, point.latitude), 16);
        } else {
          // 根据 ip 定位
          new BMap.LocalCity().get(result => {
            map.setCenter(result.name);
          });
        }
      }
    }
  };
</script>

<style scoped lang="less">
  .scroll {
    width: 100%;
    display: flex;
    flex-direction: column;
    flex: auto;
    .map-title {
      flex: none;
      height: 30px;
      line-height: 30px;
      background: #009fe2;
      color: #fff;
      font-weight: bolder;
      padding: 0 10px;
    }
    .map-sub-title {
      flex: none;
      padding: 10px;
    }
    .map-wrapper {
      flex: auto;
      position: relative;
      min-height: 420px;
    }
  }
</style>
